package org.blade.personal.controller;

import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.blade.personal.manager.codeGen.PdmTableManager;
import org.blade.personal.mode.sys.SystemUser;
import org.blade.personal.utils.KeyWords;
import org.blade.personal.utils.PropertiesUtils;
import org.blade.personal.utils.SpringMvcUtils;
import org.blade.personal.utils.pdm.Pdm;
import org.blade.personal.utils.pdm.PdmParser;
import org.blade.personal.utils.pdm.concre.SimplePdmParser;
import org.blade.personal.utils.upload.FileUploador;
import org.blade.personal.utils.upload.concre.ConcreFileUploador;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/upload/*")
public class UploadController {

	@RequestMapping("toUploadPage")
	public ModelAndView toUploadPage(){
		
		return new ModelAndView("/upload");
	}
	
	public  static final Logger logger = Logger.getLogger(UploadController.class.getName());

	@Resource
	private PdmTableManager tableManager;
	
	/**
	 * 上传
	 */
	@ResponseBody
	@RequestMapping("upload")
	public void upload(@RequestParam MultipartFile[] files) {

		HttpSession session = SpringMvcUtils.getHttpSession();
		SystemUser user = (SystemUser) session.getAttribute(KeyWords.USER_INFO);
		long userId = user.getId();
		String uuid = user.getUuid();
		FileUploador fileUploador = new ConcreFileUploador();
		String userUploadPath = PropertiesUtils.getProperties("system", "UPLOAD_FILE_PATH") + File.separator + userId;
		fileUploador.ensureFileExisted(userUploadPath);
		for (MultipartFile file : files) {
			if (file.isEmpty()) {
				logger.info("文件未上传");
				continue;
			}
			logger.info("文件长度: " + file.getSize());
			logger.info("文件类型: " + file.getContentType());
			logger.info("文件名称: " + file.getName());
			logger.info("文件原名: " + file.getOriginalFilename());
			try {
				
				PdmParser pdmParser = new SimplePdmParser();
				Pdm pdm = pdmParser.parseXml2Pdm(file.getInputStream());
				
				tableManager.saveTable(pdm.getTables());
				return;
				/*fileUploador.writeToFile(file.getInputStream(), userUploadPath + File.separator + file.getOriginalFilename());
				return;*/
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}
